﻿
// MainFrm.cpp : CMainFrame 类的实现
//

#include "stdafx.h"
#include "GIPSforDbg.h"

#include "MainFrm.h"
#include "share.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif


int save_num=0;
double xyzt[4];
double svxyz[maxnumb][3];
double bsvxyz[maxnumb][3];
double rsvxyz[maxnumb][3];
int satnum[3];
int UserView;
int GridView;
BS_PR_CR_JH staInfo;
VBS_PR_CR gridInfo;

// CMainFrame
CMainFrame *g_pCMainFrame = 0;
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWndEx)

const int  iMaxUserToolbars = 10;
const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40;
const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1;

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWndEx)
	ON_WM_CREATE()
	ON_COMMAND(ID_VIEW_CUSTOMIZE, &CMainFrame::OnViewCustomize)
	ON_REGISTERED_MESSAGE(AFX_WM_CREATETOOLBAR, &CMainFrame::OnToolbarCreateNew)
	ON_COMMAND_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnApplicationLook)
	ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnUpdateApplicationLook)
	ON_WM_SETTINGCHANGE()
	ON_WM_TIMER()
	ON_COMMAND(ID_RUN, &CMainFrame::OnRun)
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // 状态行指示器
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

// CMainFrame 构造/析构

CMainFrame::CMainFrame()
{
	// TODO: 在此添加成员初始化代码
	theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2008);

	g_pCMainFrame = this;

	for(int i=0;i<GRIDNUM;i++)
	{
		m_bCan_gridboard[i]=false;
		m_preinput_second_grid[i]=0;
		m_curinput_second_grid[i]=0;//当前的时间
		ZeroMemory(&m_szSendBuffer[i], sizeof(m_szSendBuffer[i]));
	}
	for(int i=0;i<GRIDNUM;i++)
	{
		m_sendLength[i] = 0;
	}

	ZeroMemory(&m_szSendBuffer, sizeof(m_szSendBuffer));
	ZeroMemory(&m_szRecvbuffer, sizeof(m_szRecvbuffer));

	m_rtcmSecond = 0;
	m_j = 0;
	m_bStationConnected = FALSE;

	m_Hours = 0;
	m_Minutes = 0;
	m_Seconds = 0;
	m_Secondsofweek = 0;
	//5.状态变量
	m_bServerCreated = FALSE;

	m_nCurrentSelect = -1;
	//////////////////////////////////////////////////////////////////////////
	// TODO: add member initialization code here
	m_bClientConnected = FALSE;

	m_iServerIndex = 0;
	m_nNo = 0;
	m_gpsweek = 0;
	m_secofweek = 0;
	m_bCanFinalCAL = false;
	m_sow=0.0;
	UserView=-1;
	GridView=-1;
	memset(&staInfo,0x00,sizeof(staInfo));
	memset(&gridInfo,0x00,sizeof(gridInfo));

	for (int i = 0; i<MAX_CONNECTION; i++)
	{
		m_nDOY[i] = 0;
		m_CANRecordOriData[i] = FALSE;
		ZeroMemory(&m_raw[i], sizeof(m_raw[i]));
		ZeroMemory(&m_rtcm[i], sizeof(m_rtcm[i]));
		ZeroMemory(&m_iofh[i], sizeof(IOFH));
		m_bCurrentEpoch[i][0] = TRUE;//第一次匹配标志
		m_bCurrentEpochGLO[i][0] = TRUE;
		m_bCurrentEpochBDS[i][0] = TRUE;
		for (int j = 1; j<MAXT; j++)
		{
			m_bCurrentEpoch[i][j] = FALSE;
			m_bCurrentEpochGLO[i][j] = FALSE;
			m_bCurrentEpochBDS[i][j] = FALSE;

		}
		m_bChangeFile[i] = FALSE;
		m_nFileChangeTime[i] = 0;
		for (int j = 0; j<MAXT; j++)
		{
			m_nMatchflag[i][j] = 0;
		}

	}

	for (int i = 0; i<MAXT; i++)
	{
		m_MatrixLast[i] = 0;
		m_MatrixTarget[i] = 0;
		m_MatchEpochNum[i] = 0;
	}
	for (int i = 0; i<MAXPRNGPS + MAXPRNCMP; i++)
	{
		m_prn[i] = 0;
	}
	for (int i = 0; i<3; i++)
	{
		m_dcal_delt_XYZ[i] = 0;
	}
	for (int i = 0; i<MCHN; i++)
	{
		m_iclk_prn[i] = 0;
		m_dclk_CLK[i] = 0;
		m_dSISMA[i] = 0;
		m_iBDSISMA[i] = 0;
	}



	m_TargetT = 0;

	m_bCANCal = FALSE;
	m_bGPSEphemeris = FALSE;

	m_strCurAppDir = _T("");
	m_nCanCalEpoch0 = 0;
	m_nCanCalEpochFinal = 0;

	for (int i = 0; i<MAXT; i++)
	{
		m_cutow[i] = 0;
	}

	//创建作业保存目录
	// find the file  exist or not
	CString strtemp = m_strCurAppDir + "\\AllStationDATA\\";
	/*LPCTSTR   lpszFileName;*/
	WIN32_FIND_DATA   wfd;
	BOOL   bRet;
	HANDLE   hFind;
	hFind = FindFirstFile(strtemp, &wfd);
	bRet = hFind != INVALID_HANDLE_VALUE;
	FindClose(hFind);
	if (!bRet)
	{
		CreateDirectory(strtemp, NULL);
	}

	m_liyuan_sum = 0;
	m_deltMeanN = 0;
	m_deltMeanE = 0;
	m_deltMeanU = 0;

	m_MeandeltN = 0;
	m_MeandeltE = 0;
	m_MeandeltU = 0;

	m_Meandelt40N = 0;
	m_Meandelt40E = 0;
	m_Meandelt40U = 0;

	m_deltN = 0;
	m_deltE = 0;
	m_deltU = 0;


	for (int i = 0; i<41; i++)
	{
		m_N40[i] = 0;
		m_E40[i] = 0;
		m_U40[i] = 0;

		m_Nn[i] = 0;
		m_En[i] = 0;
		m_Un[i] = 0;
	}
	m_40sum = 0;

	if (StationNum_USED <= 5)
	{
		m_limen = StationNum_USED - 1;//因为只以基准站为参考，基准站本身又不算;	
	}
	if (StationNum_USED >= 6)
	{
		m_limen = StationNum_USED - 2;//因为只以基准站为参考，基准站本身又不算;	
	}

	for (int i = 0; i<3; i++)
	{
		m_NRTDXYZ[i] = 0;
	}
	m_NRTDt = 0;
	m_ERROR = FALSE;

	//m_strpositionInfor = "";
	//for (int i = 0; i < MAX_CLIENT_COUNT;i++)
	//{
	//	m_bCanSendData[i]=FALSE;
	//}
	//ZeroMemory(&m_tagboard_DGNSS, sizeof(m_tagboard_DGNSS));
	//ZeroMemory(&m_board_del_XYZ, sizeof(m_board_del_XYZ));
	ZeroMemory(&m_szSendBuffer, sizeof(m_szSendBuffer));
	ZeroMemory(&m_szRecvbuffer, sizeof(m_szRecvbuffer));

	//m_sol.time.sec = 0;
	//m_sol.time.time = 0;
	//ZeroMemory(&m_sol, sizeof(sol_t));
	ZeroMemory(&m_prn0, sizeof(m_prn0));
	m_sendlength = 0;

	m_GPS_VPL  = 0;
	m_GPS_HPL  = 0;
	m_BDS_VPL  = 0;
	m_BDS_HPL  = 0;
	m_GNSS_VPL = 0;
	m_GNSS_HPL = 0;
	m_XPL_Index = 0;

	memset(Save_BBPC,0x00,sizeof(Save_BBPC));
	memset(re_sow,0x00,sizeof(re_sow));
	memset(&GRID0,0x00,sizeof(GRID0));
	memset(m_G_C_COOR,0x00,sizeof(m_G_C_COOR));
	GRID0.LONG0= atof(m_GNSSNetParse.m_strLONG0);
	GRID0.DLONG=atof(m_GNSSNetParse.m_strDLONG);
	GRID0.LAT0=atof(m_GNSSNetParse.m_strLAT0);
	GRID0.DLAT=atof(m_GNSSNetParse.m_strDLAT);
	GRID0.NLONG=m_GNSSNetParse.m_nNLONG;
	GRID0.NLAT=m_GNSSNetParse.m_nNLAT;

	abc=0;
	m_cNDGNSS.ProduceGridCenterCoor(GRID0,m_G_C_COOR);
}

CMainFrame::~CMainFrame()
{
	_fcloseall();


}
UINT SendThread(LPVOID lpParameter)//rver服务器发送数据线程
{
		g_pCMainFrame->m_SendSocks = accept(g_pCMainFrame->m_SendlistSock, NULL, NULL);
		sockaddr_in   addrClientName;
		int nAddLen = sizeof(addrClientName);
		getpeername(g_pCMainFrame->m_SendSocks, (sockaddr*)&addrClientName, &nAddLen);
		CString strClientIP = _T("");
		strClientIP.Format("%3d.%3d.%3d.%3d", addrClientName.sin_addr.S_un.S_un_b.s_b1, addrClientName.sin_addr.S_un.S_un_b.s_b2, addrClientName.sin_addr.S_un.S_un_b.s_b3, addrClientName.sin_addr.S_un.S_un_b.s_b4);

		if (g_pCMainFrame->m_SendSocks == INVALID_SOCKET)
		{
			//pThis->m_wndOutput.m_wndOutputMessage.AddString(_T("INVALID_SOCKET:") + strClientIP);
		}
		else
		{
			//启动线程，准备接受另一个请求
			//AfxBeginThread(Sendthread, pThis);
			while (TRUE)
			{
				CTime time;
				time = CTime::GetCurrentTime();
				int hour = time.GetHour();
				int minute = time.GetMinute();
				int second = time.GetSecond();

				int sendbyte[GRIDNUM] ={0};
				CString str = _T("");
				if (g_pCMainFrame->m_SendSocks != NULL)
				{
					for(int i=0;i<GRIDNUM ;i++)
					{
						if(fabs(double(g_pCMainFrame->m_curinput_second_grid[i]-g_pCMainFrame->m_preinput_second_grid[i]))>=1.0)				
						{
							g_pCMainFrame->m_curinput_second_grid[i]=g_pCMainFrame->m_preinput_second_grid[i];
							g_pCMainFrame->m_bCan_gridboard[i]=true;
						}
						if(g_pCMainFrame->m_bCan_gridboard[i]==true)
						{
							g_pCMainFrame->m_bCan_gridboard[i]=false;
							if (g_pCMainFrame->m_sendLength[i]>0)//nd grid 
							{ 
								//	if((i==5)||(i==6)||(i==7)||(i==9)||(i==10)||(i==11)||(i==13)||(i==14)||(i==15))
								//if((i==0)||(i==1)||(i==2)||(i==3)||(i==4)||(i==5)||(i==6)||(i==7)||(i==8)||(i==9)||(i==10)||(i==11)||(i==12)||(i==13)||(i==14)||(i==15))
								if(i>=0||i<GRIDNUM)
								{              
									//dbyte = send(g_pCMainFrame->m_SendSocks, (const char*)(g_pCMainFrame->m_szSendBuffer), g_pCMainFrame->m_sendLength, 0);	
									sendbyte[i] = send(g_pCMainFrame->m_SendSocks, (const char*)(g_pCMainFrame->m_szSendBuffer[i]), g_pCMainFrame->m_sendLength[i], 0);
									ZeroMemory(&g_pCMainFrame->m_szSendBuffer[i], sizeof(g_pCMainFrame->m_szSendBuffer[i]));
									Sleep(5);
								}
							}
						}
						else
						{
							sendbyte[i] = 1;
						}

						if (sendbyte[i]>1)
						{

							//ZeroMemory(&g_pCMainFrame->m_szSendBuffer, sizeof(g_pCMainFrame->m_szSendBuffer));
							g_pCMainFrame->m_sendLength[i] = 0;//1s播一次 不管重复性数据
							CString strtime, strByte;
							strtime.Format("%2d:%2d:%2d (computer time)", hour, minute, second);
							strByte.Format("%s sent %ld bytes corrections success\n ", strClientIP, sendbyte);
							str = strtime + strByte;

							//int nCount = g_pCMainFrame->m_wndOutput.m_wndOutputBuild.GetCount();  // 获取 String 数，可以删除
							//g_pCMainFrame->m_wndOutput.m_wndOutputBuild.SetTopIndex(nCount - 1);  // 显示最后一行String，可以删除
							//g_pCMainFrame->m_wndOutput.m_wndOutputBuild.AddString(str);

						}
						if (sendbyte[i] == -1 )
						{
							CString strtime, strleave;
							strtime.Format("%2d:%2d:%2d ", hour, minute, second);
							strleave.Format("%s离网 send\n", strClientIP);
							str = strtime + strleave;
							g_pCMainFrame->m_SendSocks = NULL;
							closesocket(g_pCMainFrame->m_SendSocks);
							AfxEndThread(0);
							return 0;
						}
					}				
				}
				Sleep(500);
			}
			g_pCMainFrame->m_SendSocks = NULL;
			closesocket(g_pCMainFrame->m_SendSocks);
			AfxEndThread(0);
		}
	return 0;	
}
void CMainFrame::OnTimer(UINT_PTR nIDEvent)
{

	if (m_GNSSNetParse.m_b_resultChangeFile == TRUE)
	{
		m_GNSSNetParse.m_b_resultChangeFile = FALSE;
		if (m_fpConnection != NULL)fclose(m_fpConnection);
		if (m_fpNDGNSS_USER != NULL)fclose(m_fpNDGNSS_USER);
		//if(m_CoorNWD.User_out_file!=NULL)fclose(m_CoorNWD.User_out_file);
		//  if(m_fpNDGNSS_RAIM!=NULL)fclose(m_fpNDGNSS_RAIM);//需要屏蔽掉，不然换天要死掉
		//	if(m_fpRTK!=NULL)       fclose(m_fpRTK); 
		CString strYear, strDOY;
		CTime time;
		time = CTime::GetCurrentTime();
		int year = time.GetYear();
		strYear.Format("%d_", year);
		strDOY.Format("%d_", m_GNSSNetParse.m_nDOY[0] + 1);
		CString strRe = m_strCurAppDir + "\\" + strYear + strDOY;

		if ((m_fpConnection = _fsopen(strRe + _T("Connection_results.txt"), "ab", _SH_DENYNO)) != NULL)// _SH_DENYNO:Permits read and write access.
		{
			fseek(m_fpConnection, 0, SEEK_END);
		}
		else
		{
			AfxMessageBox(_T("记录文件Connection_results.txt打开失败"));
			return;
		}

		if ((m_fpNDGNSS_USER = _fsopen(strRe + _T("NRTD_GNSS_Results.txt"), "ab", _SH_DENYNO)) != NULL)// _SH_DENYNO:Permits read and write access.
		{
			fseek(m_fpNDGNSS_USER, 0, SEEK_END);
		}
		else
		{
			AfxMessageBox(_T("记录文件NDGNSS_USER_results.txt打开失败"));
			return;
		}
		
		
	}

	CString str = _T("");
	fprintf_s(m_fpConnection, "begin***************************************************************************************************** \n");

	double ori_A[StationNum_USED][MAXT+1] = {0};
	DATG dg[StationNum_USED] = { 0 };
    //if (m_GNSSNetParse.m_bGPSBDSEphemerisArrived == FALSE)return;
	gtime_t t = { 0 }; double ep[6] = { 0 };
    #if 0
	for (int i = 0; i<StationNum_USED; i++)
	{
		//int nlist = m_GNSSNetParse.m_list_3sys_DATG[i].GetCount();=个数为MAXT+1个
		fprintf_s(m_fpConnection, "id=%d ", i);
		POSITION pos = m_GNSSNetParse.m_list_3sys_DATG[i].GetTailPosition(); 
		int j = 0; DATG datg1 = { 0 };
    	while (pos != NULL)
		{
			datg1= m_GNSSNetParse.m_list_3sys_DATG[i].GetPrev(pos);
		//	ori_A[i][j] = m_GNSSNetParse.m_list_3sys_DATG[i].GetPrev(pos).tg.second;
			ori_A[i][j] = datg1.tg.second + datg1.tg.week*604800;
			fprintf_s(m_fpConnection, "t=%16.1lf", ori_A[i][j]);
			j++;
		}
		fprintf_s(m_fpConnection, "\n");
		
	}

  

	DATG dg[StationNum_USED] = { 0 }; DATG dg_temp = { 0 };
	for (int i = 0; i < StationNum_USED; i++)
	{
		POSITION pos = m_GNSSNetParse.m_list_3sys_DATG[i].GetTailPosition();
		while (pos != NULL)
		{
			dg_temp=m_GNSSNetParse.m_list_3sys_DATG[i].GetPrev(pos);
			double corT = dg_temp.tg.second + dg_temp.tg.week * 604800;					
		}				
	}			
	gtime_t t = { 0 }; double ep[6] = { 0 };
    #endif      
	
	#pragma region Grid_PR_D
	#if 1
	///////////////////////////////////////////////////////////网格伪距差分改正数求解//////////////////////////////////////////////////////////////////
	double  xyzldz6[20], xyz2ldz6[20], xyz1ldz6[20];//xyz2ldz[20]是双系统单点定位
	double  NEUldz6[3];
	int  NO_JZZUSED;
	

	for(int h=0;h<StationNum_USED;h++)
	{
		dg[h]=m_GNSSNetParse.m_datg[h];
	}

	NO_JZZUSED = StationNum_USED ;//此处是指真正用到的作为基准站的CORS站数,不算流动站;
	DATG dg_bs[StationNum_USED+1] = { 0 },dg0 = { 0 };
	IOFH iofh_bs[StationNum_USED+1] = { 0 },ih0 = { 0 };
	for (int h = 1; h <= NO_JZZUSED; h++)//基准站ID最好从1开始，防止没数据的编号0和基准站0一样
	{
		iofh_bs[h] = m_iofh[h-1];
		dg_bs[h] = dg[h-1];
	}

	int monitor_BSdg[StationNum_USED+1];	//监测每个站是否有数据，有数据标记为1
	int sum_BSdg=0;
	memset(monitor_BSdg,0,sizeof(monitor_BSdg));

	for(int h=1; h <= NO_JZZUSED; h++)
	{
		//TRACE("m_sow=%10d,h=%2d:%10.1f,%5.1f\n",m_sow,h,dg_bs[h].tg.second,dg_bs[h].tg.second-m_sow);
		if((dg_bs[h].tg.week*604800+dg_bs[h].tg.second)!=0.0/*||fabs(dg_bs[h].tg.second-m_sow)<5*/)
		{
			/*if(h==1)
				monitor_BSdg[h]=0;
			else*/
				monitor_BSdg[h]=1;
			sum_BSdg=sum_BSdg+monitor_BSdg[h];
		}
	}

	int IWGD=99999;
	dg0=dg[0];
	ih0=m_iofh[0];
	GPST BST[GRIDNUM];//当基准站历元同步时，记录的历元时刻，进行格网改正数信息生成
	BS_PR_CR_JH BBPC[StationNum_USED+1];
	VBS_PR_CR V_BPC[GRIDNUM];
	int bst_index_sum[GRIDNUM];
	rp rcoor0;
	memset(BST,0x00,sizeof(BST));
	memset(BBPC,0x00,sizeof(BBPC));
	memset(V_BPC,0x00,sizeof(V_BPC));
	memset(bst_index_sum,0,sizeof(bst_index_sum));
	memset(&rcoor0,0x00,sizeof(rcoor0));

	//m_cNDGNSS.TraceInfo(_T("Produce reference station corrcetion Runing"));
	for(int h = 1; h <=NO_JZZUSED; h++)
	{
		if(monitor_BSdg[h]==1)
		{
			m_cNDGNSS.Produce_ReferenceStation_Corrcetion_gps_bds_glo(dg_bs[h],m_GNSSNetParse.m_GEPH,iofh_bs[h],BBPC[h]);//单站改正数信息生成

			for(int n_grid=0;n_grid<GRID0.NLAT*GRID0.NLONG;n_grid++)
			{
				Save_BBPC[n_grid][h]=BBPC[h];//将每站信息存于缓冲区
			}
		}
	}



	memset(svxyz,0x00,sizeof(svxyz));
	memset(bsvxyz,0x00,sizeof(bsvxyz));
	memset(rsvxyz,0x00,sizeof(rsvxyz));
	memset(satnum,0,sizeof(satnum));
	memset(xyzt,0x00,sizeof(xyzt));
	memset(&staInfo,0x00,sizeof(staInfo));
	double pdoptemp=0.0;
	if(UserView!=-1)
	{
		staInfo=BBPC[UserView+1];

		dg0=dg[UserView];
		ih0=m_iofh[UserView];
		//GPS/BDS/GLO单点定位,ZHOUWANZHEN161027
		m_cNDGNSS.Produce_Receiver_COOR_3SYS(dg0,m_GNSSNetParse.m_GEPH,rcoor0,svxyz,bsvxyz,rsvxyz,pdoptemp,satnum);
		xyz1ldz6[0]=rcoor0.X;
		xyz1ldz6[1]=rcoor0.Y;
		xyz1ldz6[2]=rcoor0.Z;
		xyzt[0]=rcoor0.X;
		xyzt[1]=rcoor0.Y;
		xyzt[2]=rcoor0.Z;

		//CString strContext;  
		//strContext.Format("X=%12.3f,Y=%12.3f,Z=%12.3f",rcoor0.X,rcoor0.Y,rcoor0.Z);  
		//m_wndOutput.AddStrToOutputBuild(strContext);
	}

	//m_cNDGNSS.Produce_Receiver_COOR(dg0,m_GNSSNetParse.m_GEPH,ih0,rcoor0);//流动站单点定位，更改160905！！！！！！！！
	//TRACE("%8.1f %14.3f%14.3f%14.3f %2d %2d %2d\n",dg0.tg.second,rcoor0.X,rcoor0.Y,rcoor0.Z,rcoor0.ngps,rcoor0.nbds,rcoor0.nglo);

	double M_coor[3];
	double Grid_Center_Coor[6];
	GridAttribute GridValue[GRIDNUM];//所需要的格网属性信息
	memset(GridValue,0x00,sizeof(GridValue));
	memset(Grid_Center_Coor,0x00,sizeof(Grid_Center_Coor));
	M_coor[0]=ih0.xyz[0];
	M_coor[1]=ih0.xyz[1];
	M_coor[2]=ih0.xyz[2];
	IWGD=m_cNDGNSS.Search_GridID(M_coor,GRID0,m_G_C_COOR);//搜索流动站需要的改正数所在格网的ID
	
	for(int n_grid=0;n_grid<GRID0.NLAT*GRID0.NLONG;n_grid++)//生成所有格网属性信息,其实在这一过程中，就已经剔除了没有数据的站
	{
		m_cNDGNSS.Choose_BaseStation_for_Grid(iofh_bs,NO_JZZUSED,GRID0,m_G_C_COOR[n_grid],n_grid,GridValue[n_grid]);
		//BST[n_grid]=BBPC[GridValue[n_grid].BS_ID[0]].tg;//每个格网时间判断引擎
	}

	if(sum_BSdg<StationNum_USED)//判断是否有基准站没有数据
	{
		for(int n_grid=0;n_grid<GRID0.NLAT*GRID0.NLONG;n_grid++)
		{
			m_cNDGNSS.Kick_Unavailable_Station(GridValue[n_grid],monitor_BSdg,NO_JZZUSED);//剔除不可用的站（没数据）
		}
	}
	else{}


	for(int n_grid=0;n_grid<GRID0.NLAT*GRID0.NLONG;n_grid++)
	{
		BST[n_grid]=m_cNDGNSS.Match_Epoch_Time(GridValue[n_grid],Save_BBPC[n_grid]);//匹配时刻
		bst_index_sum[n_grid]=m_cNDGNSS.Kick_Delay_Station(GridValue[n_grid],Save_BBPC[n_grid],BST[n_grid]);//剔除延迟的站并返回可用基准站数
	}


	int wgddd=IWGD;//流动站所在的格网
	int CORR_index[GRIDNUM];
	memset(CORR_index,0,sizeof(CORR_index));
	//m_cNDGNSS.TraceInfo(_T("Produce grid center corrcetion Runing"));
	for(int n_grid=0;n_grid<GRID0.NLAT*GRID0.NLONG;n_grid++)
	{
		if(GridValue[n_grid].BS_Num>=3&&bst_index_sum[n_grid]==GridValue[n_grid].BS_Num)//判断BST该历元是否在每个站中都有更新到,都更新到，进行改正数生成
		{

			CORR_index[n_grid]=1;//如果时刻都更新到，标记为1，进行下面流动站差分定位的依据
			//TRACE("m_sow=%10d,n_grid=%2d:%10.1f,%5.1f, G=%3d,C=%3d\n",m_sow,n_grid,BST[n_grid].second,BST[n_grid].second-m_sow,V_BPC[n_grid].G_num,V_BPC[n_grid].C_num);
			int gridID=n_grid;
			if(int(re_sow[n_grid])!=int(BST[n_grid].second)&&int(BST[n_grid].second)!=0)
			{
				
				re_sow[n_grid]=BST[n_grid].second;
				m_cNDGNSS.NWDGNSS_MAIN_MATCH_gps_bds_glo(Save_BBPC[n_grid],BST[n_grid],GridValue[n_grid],V_BPC[n_grid]);//调用临时变量，计算BST时刻的n_grid格网改正信息
				memset(Save_BBPC[n_grid],0x00,sizeof(Save_BBPC[n_grid]));
				//TRACE("m_sow=%10d,n_grid=%2d:%10.1f,%5.1f, G=%3d,BBG=%3d\n",m_sow,n_grid,BST[n_grid].second,BST[n_grid].second-m_sow,V_BPC[n_grid].G_num,BBPC_Temp[n_grid]);
		
				Sate_NUM sate_num0[GRIDNUM];
				memset(sate_num0,0x00,sizeof(sate_num0));

				if(GridValue[n_grid].Monitor_BS_ID!=0)//监测站,时间匹配问题！！！！
				{
					//m_cNDGNSS.NWDGNSS_3SYS_MONITOR_POS_MODULE_RAIM(GridValue[n_grid],V_BPC, dg_bs, m_GNSSNetParse.m_GEPH,iofh_bs,sate_num0);
				}

				if(n_grid==GridView)//将点选的网格信息传递给全局变量
				{
					memset(&gridInfo,0x00,sizeof(gridInfo));
					gridInfo=V_BPC[n_grid];
				}

				if(V_BPC[gridID].G_num>0||V_BPC[gridID].C_num>0||V_BPC[gridID].R_num>0)
				{
					m_rtcm_grid[gridID].nGPSNum = V_BPC[gridID].G_num;        //GPS卫星数
					m_rtcm_grid[gridID].nBDSNum = V_BPC[gridID].C_num;        //BDS卫星数
					m_rtcm_grid[gridID].nGLONum = V_BPC[gridID].R_num;        //GLO卫星数
					m_rtcm_grid[gridID].GPSWeek = BST[gridID].week;           //GPS周
					m_rtcm_grid[gridID].SecondofGPSWeek = BST[gridID].second; //GPS周内秒
					for(int iii=0;iii<V_BPC[gridID].G_num;iii++)
					{
						m_rtcm_grid[gridID].ssr[iii].prn = V_BPC[gridID].G_PRN[iii];    //GPS卫星PRN号
						m_rtcm_grid[gridID].ssr[iii].griddelay = V_BPC[gridID].GPC[iii];//GPS卫星伪距改正数
						if(iii==0)
						{
							fprintf(/*m_fpNDGNSS_USER*/m_cNDGNSS.BPC_fil,"BBPC  %6.f Grid%2d GN%2d CN%2d RN%2d * G%3d%8.3f *",BST[gridID].second,gridID+1,V_BPC[gridID].G_num,V_BPC[gridID].C_num,V_BPC[gridID].R_num,V_BPC[gridID].G_PRN[iii],V_BPC[gridID].GPC[iii]);
							TRACE("%6.f,Grid%2d,GN%2d,CN%2d,RN%2d,G%3d%8.3f,",BST[gridID].second,gridID+1,V_BPC[gridID].G_num,V_BPC[gridID].C_num,V_BPC[gridID].R_num,V_BPC[gridID].G_PRN[iii],V_BPC[gridID].GPC[iii]);
						}
						else
						{
							fprintf(/*m_fpNDGNSS_USER*/m_cNDGNSS.BPC_fil," G%3d%8.3f *",V_BPC[gridID].G_PRN[iii],V_BPC[gridID].GPC[iii]);
							TRACE("G%3d%8.3f,",V_BPC[gridID].G_PRN[iii],V_BPC[gridID].GPC[iii]);
						}
					}
					TRACE("\n                             ");
					for(int jjj=0;jjj<V_BPC[gridID].C_num;jjj++)
					{
						m_rtcm_grid[gridID].ssr[m_rtcm_grid[gridID].nGPSNum+jjj].prn = V_BPC[gridID].C_PRN[jjj];    //BDS卫星PRN号
						m_rtcm_grid[gridID].ssr[m_rtcm_grid[gridID].nGPSNum+jjj].griddelay = V_BPC[gridID].CPC[jjj];//BDS卫星伪距改正数
						fprintf(/*m_fpNDGNSS_USER*/m_cNDGNSS.BPC_fil," C%3d%8.3f *",V_BPC[gridID].C_PRN[jjj],V_BPC[gridID].CPC[jjj]);
						TRACE("C%3d%8.3f,",V_BPC[gridID].C_PRN[jjj],V_BPC[gridID].CPC[jjj]);
					}
					TRACE("\n                             ");
					int nGPSBDS = m_rtcm_grid[gridID].nGPSNum + m_rtcm_grid[gridID].nBDSNum;
					for(int jjj=0;jjj<V_BPC[gridID].R_num;jjj++)
					{
						m_rtcm_grid[gridID].ssr[nGPSBDS+jjj].prn = V_BPC[gridID].R_PRN[jjj];    //GLO卫星PRN号
						m_rtcm_grid[gridID].ssr[nGPSBDS+jjj].griddelay = V_BPC[gridID].RPC[jjj];//GLO卫星伪距改正数
						fprintf(/*m_fpNDGNSS_USER*/m_cNDGNSS.BPC_fil," R%3d%8.3f *",V_BPC[gridID].R_PRN[jjj],V_BPC[gridID].RPC[jjj]);
						TRACE("R%3d%8.3f,",V_BPC[gridID].R_PRN[jjj],V_BPC[gridID].RPC[jjj]);
					}
					fprintf(/*m_fpNDGNSS_USER*/m_cNDGNSS.BPC_fil,"\n");
					TRACE("\n");
				}
				else{}
			}
			else{}
		}
		else {}
	}

	#if 0 
	if(IWGD!=99999)
		m_sow=V_BPC[IWGD].tg.second;
	if(IWGD!=99999&&fabs(dg0.tg.second-m_sow)<=5.0&&dg0.tg.second!=0.0&&m_sow!=0.0)//流动站网格伪距差分定位
	{
		Sate_NUM sate_num1={0};
		rp rcoor00={0};
		int IWGD0=GridValue[IWGD].Grid_ID;//流动站所在的格网

		GPST Time_Now;//流动站当前匹配时刻
		int vbpc_g=0,vbpc_c=0,dg0_g=0,dg0_c=0;
		memset(&Time_Now,0x00,sizeof(Time_Now));

		Time_Now=dg0.tg;
		m_cNDGNSS.NWDGNSS_MOVING_POS_MODULE_RAIM(GridValue[IWGD],xyz1ldz6,V_BPC,dg0, m_GNSSNetParse.m_GEPH,rcoor00,sate_num1);
		vbpc_g=V_BPC[IWGD].G_num;
		vbpc_c=V_BPC[IWGD].C_num;
		dg0_g=dg0.nGPS;
		dg0_c=dg0.nBDS;

		if(Time_Now.second!=0.0&&Time_Now.week!=0)
		{
			gtime_t gtt=m_cNDGNSS.gpst2time(Time_Now.week,Time_Now.second);
			m_cNDGNSS.time2epoch(gtt,ep);

			double xyz[3]={0},NEU[3]={0},NEUldz[3]={0},xyzldz[3];
			xyz[0]=rcoor00.X;xyz[1]=rcoor00.Y;xyz[2]=rcoor00.Z;
			xyzldz[0]=xyz1ldz6[0];xyzldz[1]=xyz1ldz6[1];xyzldz[2]=xyz1ldz6[2];
			m_cNDGNSS.XYZ2NEU(ih0.xyz,xyz,NEU);
			//m_cNDGNSS.XYZ2NEU(ih0.xyz,xyzldz,NEUldz);
			if (Time_Now.second != m_cNDGNSS.m_second && rcoor00.X != 0 &&IWGD0!=99999 && fabs(NEU[0])<=100)
			{
				fprintf(m_fpNDGNSS_USER, "NWD %02.0f-%02.0f-%02.0f %6d %12.3f %12.3f %12.3f %8.3f %8.3f %8.3f %12.3f %12.3f %12.3f %03d %02d %02d %02d %02d %02d %02d  %12.3f %12.3f %6.3f %6.3f\n",
						ep[3], ep[4], ep[5],int(Time_Now.second),
						rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2],
						xyzldz[0],xyzldz[1],xyzldz[2],/*NEUldz[0],NEUldz[1],NEUldz[2],*/
						IWGD0+1,vbpc_g,vbpc_c,dg0_g,dg0_c,sate_num1.MM2,sate_num1.KK2,
						sate_num1.M2_P1,sate_num1.M2_P2,sate_num1.PDOP2,sate_num1.GDOP2);
						//日-时-分-秒 伪距差分结果,伪距差分结果NEU,单点定位结果,单点定位NEU;
							
				TRACE("$网格伪距差分定位,所在网格ID=%02d,周内秒SOW=%8.1f,差分定位结果（X=%12.3f,Y=%12.3f,Z=%12.3f）,NEU分量残差（N=%8.3f,E=%8.3f,U=%8.3f）\n",IWGD+1,Time_Now.second,rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2]);
				m_cNDGNSS.m_second=Time_Now.second;
			}
			else{}
		}
	}
	else {}
#endif

#if 0
	
	double sow=0.0;
	if(IWGD!=99999)
		sow=V_BPC[IWGD].tg.second;
	if(IWGD!=99999&&CORR_index[IWGD]==1&&fabs(dg0.tg.second-sow)<=5.0&&dg0.tg.second!=0.0&&sow!=0.0)//流动站网格伪距差分定位
	{
		Sate_NUM sate_num1={0};
		rp rcoor00={0};
		int IWGD0=GridValue[IWGD].Grid_ID;//流动站所在的格网

		GPST Time_Now;//流动站当前匹配时刻
		int vbpc_g=0,vbpc_c=0,vbpc_r=0,dg0_g=0,dg0_c=0,dg0_r=0;
		memset(&Time_Now,0x00,sizeof(Time_Now));
		int getPRC_eph=-1;
		int getDT=-1;

		Time_Now=dg0.tg;
		m_cNDGNSS.NWDGNSS_3SYS_MOVING_POS_MODULE_RAIM(GridValue[IWGD],xyz1ldz6,V_BPC,dg0, m_GNSSNetParse.m_GEPH,rcoor00,sate_num1);
		vbpc_g=V_BPC[IWGD].G_num;
		vbpc_c=V_BPC[IWGD].C_num;
		vbpc_r=V_BPC[IWGD].R_num;
		dg0_g=dg0.nGPS;
		dg0_c=dg0.nBDS;
		dg0_r=dg0.nGLO;

		if(Time_Now.second!=0.0&&Time_Now.week!=0)
		{
			gtime_t gtt=m_cNDGNSS.gpst2time(Time_Now.week,Time_Now.second);
			m_cNDGNSS.time2epoch(gtt,ep);

			double xyz[3]={0},NEU[3]={0},NEUldz[3]={0},NEU0[3]={0},xyzldz[3];
			xyz[0]=rcoor00.X;xyz[1]=rcoor00.Y;xyz[2]=rcoor00.Z;
			xyzldz[0]=xyz1ldz6[0];xyzldz[1]=xyz1ldz6[1];xyzldz[2]=xyz1ldz6[2];
			m_cNDGNSS.XYZ2NEU(ih0.xyz,xyz,NEU);
			m_cNDGNSS.XYZ2NEU(ih0.xyz,xyzldz,NEUldz);
			m_cNDGNSS.XYZ2NEU(xyzldz,xyz,NEU0);
			if (Time_Now.second != m_cNDGNSS.m_second && rcoor00.X != 0 &&IWGD0!=99999 && fabs(NEU[0])<=100)
			{fprintf(m_fpNDGNSS_USER, "NWD  %2.0f-%2.0f-%2.0f-%9d %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %8d %3d %3d %3d %3d %3d %3d %3d %3d %3d %13.3f %13.3f %13.3f %8.3f %8.3f\n",
			ep[3], ep[4], ep[5],int(Time_Now.second),
			rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2],
			xyzldz[0],xyzldz[1],xyzldz[2],NEUldz[0],NEUldz[1],NEUldz[2],
			IWGD0,vbpc_g,vbpc_c,vbpc_r,dg0_g,dg0_c,dg0_r,sate_num1.MM2,sate_num1.KK2,sate_num1.RR2,
			sate_num1.M2_P1,sate_num1.M2_P2,sate_num1.M2_P3,sate_num1.PDOP2,sate_num1.GDOP2);
			//日-时-分-秒 伪距差分结果,伪距差分结果NEU,单点定位结果,单点定位NEU;
							
			TRACE("sow=%8.1f:NG=%3d,NB=%3d,NR=%3d,X=%12.3f,Y=%12.3f,Z=%12.3f;N=%12.3f,E=%12.3f,U=%12.3f;Grid%2d\n",Time_Now.second,sate_num1.MM2,sate_num1.KK2,sate_num1.RR2,rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2],IWGD+1);

			m_cNDGNSS.m_second=Time_Now.second;
			}
			else if (Time_Now.second != m_cNDGNSS.m_second && rcoor00.X != 0 &&IWGD0!=99999 && fabs(NEU[0])>100)//跑偏;
			{fprintf(m_fpNDGNSS_USER, "XWD  %2.0f-%2.0f-%2.0f-%9d %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %8d %3d %3d %3d %3d %3d %3d %3d %3d %3d %13.3f %13.3f %13.3f %8.3f %8.3f\n",
			ep[3], ep[4], ep[5],int(Time_Now.second),
			rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2],
			xyzldz[0],xyzldz[1],xyzldz[2],NEUldz[0],NEUldz[1],NEUldz[2],
			IWGD0,vbpc_g,vbpc_c,vbpc_r,dg0_g,dg0_c,dg0_r,sate_num1.MM2,sate_num1.KK2,sate_num1.RR2,
			sate_num1.M2_P1,sate_num1.M2_P2,sate_num1.M2_P3,sate_num1.PDOP2,sate_num1.GDOP2);
			//日-时-分-秒 伪距差分结果,伪距差分结果NEU,单点定位结果,单点定位NEU;
			m_cNDGNSS.m_second=Time_Now.second;
			}
			else if (Time_Now.second == m_cNDGNSS.m_second )//重复历元;
			{fprintf(m_fpNDGNSS_USER, "RND  %2.0f-%2.0f-%2.0f-%9d %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %8d %3d %3d %3d %3d %3d %3d %3d %3d %3d %13.3f %13.3f %13.3f %8.3f %8.3f\n",
			ep[3], ep[4], ep[5],int(Time_Now.second),
			rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2],
			xyzldz[0],xyzldz[1],xyzldz[2],NEUldz[0],NEUldz[1],NEUldz[2],
			IWGD0,vbpc_g,vbpc_c,vbpc_r,dg0_g,dg0_c,dg0_r,sate_num1.MM2,sate_num1.KK2,sate_num1.RR2,
			sate_num1.M2_P1,sate_num1.M2_P2,sate_num1.M2_P3,sate_num1.PDOP2,sate_num1.GDOP2);
			//日-时-分-秒 伪距差分结果,伪距差分结果NEU,单点定位结果,单点定位NEU;
			m_cNDGNSS.m_second=Time_Now.second;
			}
			else if (Time_Now.second != m_cNDGNSS.m_second &&(rcoor00.X == 0 ||IWGD0==99999 ))//不重复历元,未解出结果或未找到网格;
			{fprintf(m_fpNDGNSS_USER, "UND  %2.0f-%2.0f-%2.0f-%9d %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %8d %3d %3d %3d %3d %3d %3d %3d %3d %3d %13.3f %13.3f %13.3f %8.3f %8.3f\n",
			ep[3], ep[4], ep[5],int(Time_Now.second),
			rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2],
			xyzldz[0],xyzldz[1],xyzldz[2],NEUldz[0],NEUldz[1],NEUldz[2],
			IWGD0,vbpc_g,vbpc_c,vbpc_r,dg0_g,dg0_c,dg0_r,sate_num1.MM2,sate_num1.KK2,sate_num1.RR2,
			sate_num1.M2_P1,sate_num1.M2_P2,sate_num1.M2_P3,sate_num1.PDOP2,sate_num1.GDOP2);
			//日-时-分-秒 伪距差分结果,伪距差分结果NEU,单点定位结果,单点定位NEU;
			m_cNDGNSS.m_second=Time_Now.second;
			}
			else 
			{fprintf(m_fpNDGNSS_USER, "SOS  %2.0f-%2.0f-%2.0f-%9d %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %13.3f %13.3f %13.3f  %8d %3d %3d %3d %3d %3d %3d %3d %3d %3d %13.3f %13.3f %13.3f %8.3f %8.3f\n",
			ep[3], ep[4], ep[5],int(Time_Now.second),
			rcoor00.X,rcoor00.Y,rcoor00.Z,NEU[0],NEU[1],NEU[2],
			xyzldz[0],xyzldz[1],xyzldz[2],NEUldz[0],NEUldz[1],NEUldz[2],
			IWGD0,vbpc_g,vbpc_c,vbpc_r,dg0_g,dg0_c,dg0_r,sate_num1.MM2,sate_num1.KK2,sate_num1.RR2,
			sate_num1.M2_P1,sate_num1.M2_P2,sate_num1.M2_P3,sate_num1.PDOP2,sate_num1.GDOP2);
			//日-时-分-秒 伪距差分结果,伪距差分结果NEU,单点定位结果,单点定位NEU;
			}
		}
	}

	else {}
#endif


	#pragma region grid_1215+i
     #if 1
	int flag=0;int type=0;int sync=0;int is_succ = 0;int sendgridLength=0;
	for(int i=0;i<GRIDNUM;i++)
	{
		type = 3001+i;//3001-3001+GRIDNUM,
		sync = 0;
		if(i==(GRIDNUM-1))
		{
			sync = 0;
		}
		is_succ = 0;
		//if (fabs(m_rtcm_grid[i].ssr[0].griddelay)>=0)//先保证要有数据,有可能是0数据？,这里加了绝对值，16.05.16，四川
		if(m_rtcm_grid[i].nGPSNum+m_rtcm_grid[i].nBDSNum+m_rtcm_grid[i].nGLONum>0)
		{
			is_succ = m_CRTCM3x.gen_rtcm3(&m_rtcm_grid[i], type, sync);
		}

		if (is_succ == 1)
		{
			flag++;
			is_succ = 0;
			m_preinput_second_grid[i] =int( m_rtcm_grid[i].SecondofGPSWeek);
			str = "";

			OutputDebugString(str);

			int numprn = m_rtcm_grid[i].nGPSNum+m_rtcm_grid[i].nBDSNum+m_rtcm_grid[i].nGLONum;
			sendgridLength = 6 + int(ceil((68 + numprn*28) / 8.0));
			memcpy(m_szSendBuffer[i], m_rtcm_grid[i].buff, sendgridLength);
			m_sendLength[i] = sendgridLength;	
		}	
		int ttttt=0;
	}
	#endif
	#pragma endregion

	#endif
	#pragma endregion
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	
	//}





	CFrameWndEx::OnTimer(nIDEvent);
}


void CMainFrame::OnRun()
{	if (m_bStationConnected == TRUE)
	{
		AfxMessageBox("已经选择站点连接！");
		return;
	}
	m_bStationConnected = TRUE;



#pragma region cal
#if 0

#endif
#pragma endregion

	for (int i = 0; i < GRIDNUM; i++)
	{
		m_CRTCM3x.init_rtcm(&m_rtcm_grid[i]);
		m_preinput_second_grid[i]=0;
	}

	m_GNSSNetParse.OnAllStationConnect();

	for (int i = 0; i < MAX_CONNECTION; i++)
	{		
		m_iofh[i] = m_GNSSNetParse.m_IOFH[i];
	}
	if (!m_GNSSNetParse.ConnectServer())
	{
		m_GNSSNetParse.CloseSocket();
		AfxMessageBox(_T("连接失败！"));
		return;
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
//启动服务端模式，电脑作为服务端

	if (!m_bServerCreated)
	{
		if (!m_psockServer->CreateServer(m_nPortLocal, 5))
		{
			AfxMessageBox("创建服务器出错!");
			return;
		}
		if (!m_psockServer->StartServer(OnStatusChange, OnDataArrived, (DWORD)this))
		{
			AfxMessageBox("启动服务出错!");
			m_psockServer->Close();
			return;
		}
		m_bServerCreated = TRUE;

	}
	else
	{
		m_psockServer->Close();
		m_bServerCreated = FALSE;
		m_nCurrentSelect = -1;
	}


#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////

	for (int i = 0; i<MAXT; i++)
	{
		m_cutow[i] = 0;
	}


	CString strPath = _T("");
	GetModuleFileName(NULL, strPath.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
	strPath.ReleaseBuffer();
	int nPos;
	nPos = strPath.ReverseFind('\\');
	strPath = strPath.Left(nPos);

	m_strCurAppDir = strPath;
	CString strtemp = m_strCurAppDir + "\\AllStationDATA\\";
	/*LPCTSTR   lpszFileName;*/
	WIN32_FIND_DATA   wfd;
	BOOL   bRet;
	HANDLE   hFind;
	hFind = FindFirstFile(strtemp, &wfd);
	bRet = hFind != INVALID_HANDLE_VALUE;
	FindClose(hFind);
	if (!bRet)
	{
		CreateDirectory(strtemp, NULL);
	}

	CTime time;
	time = CTime::GetCurrentTime();
	int year = time.GetYear();
	int month = time.GetMonth();
	int day = time.GetDay();

	int t11 = 2017 * 365 + 9 * 30 + 1;
	int tymd = year * 365 + month * 30 + day;
	if (tymd>t11){ return; }
	int doy = m_GNSSNetParse.DOY(year, month, day);
	CString strDOY;
	if (0 <= doy&& doy <= 9)
	{
		strDOY.Format("00%d_", doy);
	}
	if (10 <= doy && doy <= 99)
	{
		strDOY.Format("0%d_", doy);
	}
	if (100 <= doy&& doy <= 367)
	{
		strDOY.Format("%d_", doy);
	}
	CString strYear;
	strYear.Format("%d_", year);
	CString strRe = m_strCurAppDir + "\\" + strYear + strDOY;


	if ((m_fpConnection = _fsopen(strRe + _T("Connection_results.txt"), "ab", _SH_DENYNO)) != NULL)// _SH_DENYNO:Permits read and write access.
	{
		fseek(m_fpConnection, 0, SEEK_END);
	}
	else
	{
		AfxMessageBox(_T("记录文件Connection_results.txt打开失败"));
		return;
	}

	if ((m_fpNDGNSS_USER = _fsopen(strRe + _T("NRTD_GNSS_Results.txt"), "ab", _SH_DENYNO)) != NULL)// _SH_DENYNO:Permits read and write access.
	{	
        fseek(m_fpNDGNSS_USER, 0, SEEK_END);	
	}
	else
	{
		AfxMessageBox(_T("记录文件NDGNSS_USER_results.txt打开失败"));
		return;
	}


	WSADATA wsa = { 0 };
	WSAStartup(MAKEWORD(2, 2), &wsa);

	memset(&m_SendSocks, NULL, sizeof m_SendSocks);
	//设定地址
	m_Sendserv.sin_addr.s_addr = htonl(INADDR_ANY);
	m_Sendserv.sin_family = AF_INET;
	//	m_Sendserv.sin_port = htons(m_GNSSNetParse.m_SendLISTEN_PORT);
	int port = m_GNSSNetParse.m_nSendToServerPort;	m_Sendserv.sin_port = htons(port);
	//创建socket

	int opt = 1;
	int len = sizeof(opt);
	m_SendlistSock = socket(AF_INET, SOCK_STREAM, 0);
	setsockopt(m_SendlistSock, SOL_SOCKET, SO_REUSEADDR,(const char*)&opt, len);
	//绑定
	if (SOCKET_ERROR == bind(m_SendlistSock, (sockaddr*)&m_Sendserv, sizeof(m_Sendserv)))
	{
		//		AfxMessageBox("套接字绑定错误！");
		int ie = WSAGetLastError();

		return;
	}
	else
	{
			//ShowMsg("服务器创建成功\r\n");
		//开始侦听	
		listen(m_SendlistSock, SOMAXCONN);
		//调用线程
		AfxBeginThread(&SendThread, this);
	}

	SetTimer(1, 1000, NULL);
	
	
}


int CMainFrame::MatchEpoch(double &target_pri, double A[StationNum_USED][MAXT + 1], int &match_num, double A_match[MAXT + 1])
{
	
	for (int i_baseT = 0; i_baseT < MAXT + 1; i_baseT++)
	{
		int match_epoch_num = 0;
		double t_base = A[0][i_baseT];
		if (t_base>target_pri)
		{
			for (int i_ref_S = 1; i_ref_S < StationNum_USED; i_ref_S++)
			{
				for (int i_refT = 0; i_refT < MAXT + 1; i_refT++)
				{
					double t_ref = A[i_ref_S][i_refT];
					if (fabs(t_base - t_ref)<0.1)
					{
						match_epoch_num++;
					}
				}


			}
			if (match_epoch_num == StationNum_USED-1)//基准站自身不算
			{

				A_match[match_num] = t_base;
				match_num++;
				match_epoch_num = 0;
			}

		}

		
	}
	if (match_num >0)
	{
		target_pri = A_match[0];
	}
	return match_num;

}


void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
	CFrameWndEx::OnSettingChange(uFlags, lpszSection);
	m_wndOutput.UpdateFonts();
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWndEx::OnCreate(lpCreateStruct) == -1)
		return -1;

	BOOL bNameValid;

	if (!m_wndMenuBar.Create(this))
	{
		TRACE0("未能创建菜单栏\n");
		return -1;      // 未能创建
	}

	m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY);

	// 防止菜单栏在激活时获得焦点
	CMFCPopupMenu::SetForceMenuFocus(FALSE);

	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME))
	{
		TRACE0("未能创建工具栏\n");
		return -1;      // 未能创建
	}

	CString strToolBarName;
	bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD);
	ASSERT(bNameValid);
	m_wndToolBar.SetWindowText(strToolBarName);

	CString strCustomize;
	bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
	ASSERT(bNameValid);
	m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);

	// 允许用户定义的工具栏操作:
	InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId);

	if (!m_wndStatusBar.Create(this))
	{
		TRACE0("未能创建状态栏\n");
		return -1;      // 未能创建
	}
	m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));

	// TODO: 如果您不希望工具栏和菜单栏可停靠，请删除这五行
	m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY);
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_wndMenuBar);
	DockPane(&m_wndToolBar);


	// 启用 Visual Studio 2005 样式停靠窗口行为
	CDockingManager::SetDockingMode(DT_SMART);
	// 启用 Visual Studio 2005 样式停靠窗口自动隐藏行为
	EnableAutoHidePanes(CBRS_ALIGN_ANY);

	// 加载菜单项图像(不在任何标准工具栏上):
	CMFCToolBar::AddToolBarForImageCollection(IDR_MENU_IMAGES, theApp.m_bHiColorIcons ? IDB_MENU_IMAGES_24 : 0);

	// 创建停靠窗口
	if (!CreateDockingWindows())
	{
		TRACE0("未能创建停靠窗口\n");
		return -1;
	}

	m_wndFileView.EnableDocking(CBRS_ALIGN_ANY);
	m_wndClassView.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_wndFileView);
	CDockablePane* pTabbedBar = NULL;
	m_wndClassView.AttachToTabWnd(&m_wndFileView, DM_SHOW, TRUE, &pTabbedBar);
	m_wndOutput.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_wndOutput);
	m_wndProperties.EnableDocking(CBRS_ALIGN_ANY);
	DockPane(&m_wndProperties);

	// 基于持久值设置视觉管理器和样式
	OnApplicationLook(theApp.m_nAppLook);

	// 启用工具栏和停靠窗口菜单替换
	EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR);

	// 启用快速(按住 Alt 拖动)工具栏自定义
	CMFCToolBar::EnableQuickCustomization();

	if (CMFCToolBar::GetUserImages() == NULL)
	{
		// 加载用户定义的工具栏图像
		if (m_UserImages.Load(_T(".\\UserImages.bmp")))
		{
			CMFCToolBar::SetUserImages(&m_UserImages);
		}
	}

	// 启用菜单个性化(最近使用的命令)
	// TODO: 定义您自己的基本命令，确保每个下拉菜单至少有一个基本命令。
	CList<UINT, UINT> lstBasicCommands;

	lstBasicCommands.AddTail(ID_FILE_NEW);
	lstBasicCommands.AddTail(ID_FILE_OPEN);
	lstBasicCommands.AddTail(ID_FILE_SAVE);
	lstBasicCommands.AddTail(ID_FILE_PRINT);
	lstBasicCommands.AddTail(ID_APP_EXIT);
	lstBasicCommands.AddTail(ID_EDIT_CUT);
	lstBasicCommands.AddTail(ID_EDIT_PASTE);
	lstBasicCommands.AddTail(ID_EDIT_UNDO);
	lstBasicCommands.AddTail(ID_APP_ABOUT);
	lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR);
	lstBasicCommands.AddTail(ID_VIEW_TOOLBAR);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2003);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_VS_2005);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLUE);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_SILVER);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLACK);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_AQUA);
	lstBasicCommands.AddTail(ID_VIEW_APPLOOK_WINDOWS_7);
	lstBasicCommands.AddTail(ID_SORTING_SORTALPHABETIC);
	lstBasicCommands.AddTail(ID_SORTING_SORTBYTYPE);
	lstBasicCommands.AddTail(ID_SORTING_SORTBYACCESS);
	lstBasicCommands.AddTail(ID_SORTING_GROUPBYTYPE);

	CMFCToolBar::SetBasicCommands(lstBasicCommands);

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWndEx::PreCreateWindow(cs) )
		return FALSE;
	// TODO: 在此处通过修改
	//  CREATESTRUCT cs 来修改窗口类或样式

	return TRUE;
}

BOOL CMainFrame::CreateDockingWindows()
{
	BOOL bNameValid;

	// 创建类视图
	CString strClassView;
	bNameValid = strClassView.LoadString(IDS_CLASS_VIEW);
	ASSERT(bNameValid);
	if (!m_wndClassView.Create(strClassView, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_CLASSVIEW, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT | CBRS_FLOAT_MULTI))
	{
		TRACE0("未能创建“类视图”窗口\n");
		return FALSE; // 未能创建
	}

	// 创建文件视图
	CString strFileView;
	bNameValid = strFileView.LoadString(IDS_FILE_VIEW);
	ASSERT(bNameValid);
	if (!m_wndFileView.Create(strFileView, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_FILEVIEW, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_LEFT| CBRS_FLOAT_MULTI))
	{
		TRACE0("未能创建“文件视图”窗口\n");
		return FALSE; // 未能创建
	}

	// 创建输出窗口
	CString strOutputWnd;
	bNameValid = strOutputWnd.LoadString(IDS_OUTPUT_WND);
	ASSERT(bNameValid);
	if (!m_wndOutput.Create(strOutputWnd, this, CRect(0, 0, 100, 100), TRUE, ID_VIEW_OUTPUTWND, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_BOTTOM | CBRS_FLOAT_MULTI))
	{
		TRACE0("未能创建输出窗口\n");
		return FALSE; // 未能创建
	}

	// 创建属性窗口
	CString strPropertiesWnd;
	bNameValid = strPropertiesWnd.LoadString(IDS_PROPERTIES_WND);
	ASSERT(bNameValid);
	if (!m_wndProperties.Create(strPropertiesWnd, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_PROPERTIESWND, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_RIGHT | CBRS_FLOAT_MULTI))
	{
		TRACE0("未能创建“属性”窗口\n");
		return FALSE; // 未能创建
	}

	SetDockingWindowIcons(theApp.m_bHiColorIcons);
	return TRUE;
}

void CMainFrame::SetDockingWindowIcons(BOOL bHiColorIcons)
{
	HICON hFileViewIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_FILE_VIEW_HC : IDI_FILE_VIEW), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0);
	m_wndFileView.SetIcon(hFileViewIcon, FALSE);

	HICON hClassViewIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_CLASS_VIEW_HC : IDI_CLASS_VIEW), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0);
	m_wndClassView.SetIcon(hClassViewIcon, FALSE);

	HICON hOutputBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_OUTPUT_WND_HC : IDI_OUTPUT_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0);
	m_wndOutput.SetIcon(hOutputBarIcon, FALSE);

	HICON hPropertiesBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_PROPERTIES_WND_HC : IDI_PROPERTIES_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0);
	m_wndProperties.SetIcon(hPropertiesBarIcon, FALSE);

}

// CMainFrame 诊断

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWndEx::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWndEx::Dump(dc);
}
#endif //_DEBUG


// CMainFrame 消息处理程序

void CMainFrame::OnViewCustomize()
{
	CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog(this, TRUE /* 扫描菜单*/);
	pDlgCust->EnableUserDefinedToolbars();
	pDlgCust->Create();
}

LRESULT CMainFrame::OnToolbarCreateNew(WPARAM wp,LPARAM lp)
{
	LRESULT lres = CFrameWndEx::OnToolbarCreateNew(wp,lp);
	if (lres == 0)
	{
		return 0;
	}

	CMFCToolBar* pUserToolbar = (CMFCToolBar*)lres;
	ASSERT_VALID(pUserToolbar);

	BOOL bNameValid;
	CString strCustomize;
	bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
	ASSERT(bNameValid);

	pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
	return lres;
}

void CMainFrame::OnApplicationLook(UINT id)
{
	CWaitCursor wait;

	theApp.m_nAppLook = id;

	switch (theApp.m_nAppLook)
	{
	case ID_VIEW_APPLOOK_WIN_2000:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManager));
		break;

	case ID_VIEW_APPLOOK_OFF_XP:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP));
		break;

	case ID_VIEW_APPLOOK_WIN_XP:
		CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
		break;

	case ID_VIEW_APPLOOK_OFF_2003:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2003));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	case ID_VIEW_APPLOOK_VS_2005:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2005));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	case ID_VIEW_APPLOOK_VS_2008:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2008));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	case ID_VIEW_APPLOOK_WINDOWS_7:
		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows7));
		CDockingManager::SetDockingMode(DT_SMART);
		break;

	default:
		switch (theApp.m_nAppLook)
		{
		case ID_VIEW_APPLOOK_OFF_2007_BLUE:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_LunaBlue);
			break;

		case ID_VIEW_APPLOOK_OFF_2007_BLACK:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);
			break;

		case ID_VIEW_APPLOOK_OFF_2007_SILVER:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);
			break;

		case ID_VIEW_APPLOOK_OFF_2007_AQUA:
			CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Aqua);
			break;
		}

		CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));
		CDockingManager::SetDockingMode(DT_SMART);
	}

	m_wndOutput.UpdateFonts();
	RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);

	theApp.WriteInt(_T("ApplicationLook"), theApp.m_nAppLook);
}

void CMainFrame::OnUpdateApplicationLook(CCmdUI* pCmdUI)
{
	pCmdUI->SetRadio(theApp.m_nAppLook == pCmdUI->m_nID);
}


BOOL CMainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext) 
{
	// 基类将执行真正的工作

	if (!CFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext))
	{
		return FALSE;
	}


	// 为所有用户工具栏启用自定义按钮
	BOOL bNameValid;
	CString strCustomize;
	bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
	ASSERT(bNameValid);

	for (int i = 0; i < iMaxUserToolbars; i ++)
	{
		CMFCToolBar* pUserToolbar = GetUserToolBarByIndex(i);
		if (pUserToolbar != NULL)
		{
			pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
		}
	}

	return TRUE;
}